package com.recharge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.ResultSupport;
import com.recharge.common.util.BeanUtilsExtends;
import com.recharge.core.entity.VoucherRecordEntity;
import com.recharge.core.mapper.VoucherRecordMapper;
import com.recharge.domain.query.VoucherRecordQueryDO;
import com.recharge.domain.vo.VoucherRecordDO;
import com.recharge.service.VoucherRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * 凭证核销记录 服务实现类
 * </p>
 *
 * @author Reagan
 * @since 2020-10-20
 */
@Service
public class VoucherRecordServiceImpl extends ServiceImpl<VoucherRecordMapper, VoucherRecordEntity> implements VoucherRecordService {

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO add(VoucherRecordDO domain) {

        VoucherRecordEntity entity = new VoucherRecordEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        entity.setVerificationDate(Calendar.getInstance().getTime());

        boolean res = false;
        try {
            res = this.save(entity);
            //核销记录添加成功后，根据核销的status修改充值卡的状态
            Integer status = entity.getStatus();


        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CARD_PROVIDER_ADD_PROVIDER_GOODS_ERROR);
            logger.debug("error code：" + ErrorCode.CARD_PROVIDER_ADD_PROVIDER_GOODS_ERROR.getCode() + " msg" + ErrorCode.CARD_PROVIDER_ADD_PROVIDER_GOODS_ERROR.getMsg());
            return result;
        }
        //
        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO edit(VoucherRecordDO domain) {

        VoucherRecordEntity entity = new VoucherRecordEntity();

        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        boolean res = false;
        try {
            res = this.updateById(entity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        //判断r的值是否小于0.如果小于0 就代表添加失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CARD_PROVIDER_EDIT_PROVIDER_GOODS_ERROR);
            logger.debug("error code：" + ErrorCode.CARD_PROVIDER_EDIT_PROVIDER_GOODS_ERROR.getCode() + " msg" + ErrorCode.CARD_PROVIDER_EDIT_PROVIDER_GOODS_ERROR.getMsg());
            return result;
        }

        return result;
    }

    @Transactional(propagation= Propagation.SUPPORTS, rollbackFor= Exception.class)
    public ResultDO get(String id) {

        ResultDO result = new ResultSupport();
        VoucherRecordEntity entity = null;

        try {
            entity = this.getById(id);
        } catch(Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        VoucherRecordDO domain = getDomain(entity);

        result.setModel(ResultDO.FIRST_MODEL_KEY, domain);

        return result;
    }

    @Transactional(propagation= Propagation.SUPPORTS, rollbackFor= Exception.class)
    public ResultDO find(VoucherRecordQueryDO query) {
        ResultDO result = new ResultSupport();
        //创建分页对象
        Page<VoucherRecordEntity> page = new Page<>(query.getCurrentPage(), query.getPageSize());
        IPage<VoucherRecordEntity> iPage = null;
        QueryWrapper<VoucherRecordEntity> queryWrapper = new QueryWrapper<>();
        //封装动态sql

        if(StringUtils.isNotEmpty(query.getProviderOrderNo())){
            queryWrapper.lambda().eq(VoucherRecordEntity::getProviderOrderNo,query.getProviderOrderNo());
        }
        if(StringUtils.isNotEmpty(query.getOrderNo())){
            queryWrapper.lambda().eq(VoucherRecordEntity::getOrderNo,query.getOrderNo());
        }
        if(query.getStatus()!=null){
            queryWrapper.lambda().eq(VoucherRecordEntity::getStatus,query.getStatus());
        }

        try{
            iPage = baseMapper.selectPage(page, queryWrapper);
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        //取出返回正常的结果
        List<VoucherRecordEntity> voucherRecordEntityList = iPage.getRecords();
        //将实体复制到DO
        List<VoucherRecordDO> domainList = getDomainList(voucherRecordEntityList);
        PageDO<VoucherRecordDO> pageDO = new PageDO<>();

        pageDO.setCurrentPage(iPage.getCurrent());
        pageDO.setPageCount(iPage.getPages());
        pageDO.setPageSize(iPage.getSize());
        pageDO.setRowCount(iPage.getTotal());
        pageDO.setData(domainList);
        result.setModel(ResultDO.FIRST_MODEL_KEY,pageDO);

        return  result;
    }

    @Override
    @Transactional(propagation= Propagation.SUPPORTS, rollbackFor= Exception.class)
    public ResultDO findByOrderNo(VoucherRecordQueryDO domain) {
        //获取页面传入订单号
        String orderNo = domain.getOrderNo();
        //如果是null或者""直接返回
        if(!StringUtils.isNotEmpty(orderNo)||"".equals(orderNo)) return  null;
        ResultDO result = new ResultSupport();
        //数据结果集分页
        Page<VoucherRecordEntity> page = new Page<>(domain.getCurrentPage(),domain.getPageSize());
        IPage<VoucherRecordEntity> iPage = null;
        //查询条件
        QueryWrapper<VoucherRecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(VoucherRecordEntity::getOrderNo,domain.getOrderNo());
        try{
            iPage = baseMapper.selectPage(page, queryWrapper);
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        //获取集合数据
        List<VoucherRecordEntity> entityList = iPage.getRecords();
        //转换成页面对象
        List<VoucherRecordDO> domainList = this.getDomainList(entityList);
        //判断集合是否转换成功
        //判断转换是否成功
        if(domainList.size() == 0||domainList==null) {
            result.setSuccess(false);
            logger.debug("核销单根据订单号查询失败 error code : " + ErrorCode.CARD_VOUCHER_GET_ERROR.getCode() + " msg" + ErrorCode.CARD_VOUCHER_GET_ERROR.getMsg());
            result.setErrorCode(ErrorCode.CARD_VOUCHER_GET_ERROR);
            return result;
        }
        result.setModel(ResultDO.FIRST_MODEL_KEY,domainList);
        return result;
    }

    @Override
    @Transactional(propagation= Propagation.SUPPORTS, rollbackFor= Exception.class)
    public ResultDO findByProviderOrderNo(VoucherRecordQueryDO domain) {
        //获取页面传入的供应单号
        String providerOrderNo = domain.getProviderOrderNo();
        //没取到值直接返回
        if(!StringUtils.isNotEmpty(providerOrderNo)||"".equals(providerOrderNo)) return  null;
        ResultDO result = new ResultSupport();
        //数据结果集分页
        Page<VoucherRecordEntity> page = new Page<>(domain.getCurrentPage(),domain.getPageSize());
        IPage<VoucherRecordEntity> iPage = null;
        //查询条件封装
        QueryWrapper<VoucherRecordEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(VoucherRecordEntity::getProviderOrderNo,providerOrderNo);
        try{
          iPage =  baseMapper.selectPage(page,queryWrapper);
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：核销单根据供应单号查询失败" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        //获取查询的结果集
        List<VoucherRecordEntity> voucherRecordEntities = iPage.getRecords();
        //转换结果集
        List<VoucherRecordDO> domainList = this.getDomainList(voucherRecordEntities);
        if(domainList==null||domainList.size()==0){
            result.setSuccess(false);
            logger.debug(" error code : 转换结果集异常" + ErrorCode.CARD_VOUCHER_GET_ERROR.getCode() + " msg" + ErrorCode.CARD_VOUCHER_GET_ERROR.getMsg());
            result.setErrorCode(ErrorCode.CARD_VOUCHER_GET_ERROR);
            return result;
        }
        result.setModel(ResultDO.FIRST_MODEL_KEY,domainList);
        return result;
    }

    @Override
    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO editStatus(VoucherRecordDO domain) {
        //根据id修改核销单的状态
        VoucherRecordEntity voucherRecordEntity = new VoucherRecordEntity();
        //将DO对象转换成etity
        ResultDO result = BeanUtilsExtends.copy(voucherRecordEntity, domain);
        if (!result.isSuccess()) {
            logger.debug("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }
        //设置修改操作时间
        //voucherRecordEntity.set;
        boolean res = false;
        try {
            res = this.updateById(voucherRecordEntity);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.debug("error code：修改核销单状态失败" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }
        //判断res的值是true.如果不是 修改核销单状态失败
        if(!res) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.CARD_VOUCHER_EDIT_ERROR);
            logger.debug("error code：" + ErrorCode.CARD_VOUCHER_EDIT_ERROR.getCode() + " msg" + ErrorCode.CARD_VOUCHER_EDIT_ERROR.getMsg());
            return result;
        }
        return result;
    }


    private VoucherRecordDO getDomain(VoucherRecordEntity entity) {

        //判断房源对象是否为空，为空就返回 空，不为空就进行下面的代码
        if(entity == null) return null;
        VoucherRecordDO domain = new VoucherRecordDO();

        domain = BeanUtilsExtends.copyProperties(domain, entity) ? domain : null;

        //判断拷贝数据到Dto对象是否成功，如果成功则返回domian，如果不成功就返回空
        return domain;
    }

    private List<VoucherRecordDO> getDomainList(List<VoucherRecordEntity> list) {
        //创建一个名为dolist的房源do类型的 list集合
        List<VoucherRecordDO> doList = new ArrayList<VoucherRecordDO>();

        //判断传入的list的集合的size是否大于0
        if(list.size() > 0) {
            //大于0是，遍历list，创建do类型的对象 调用getdomain方法
            for(VoucherRecordEntity entity : list) {

                VoucherRecordDO domain = this.getDomain(entity);

                //判断得到的domain 是否为空 不为空 就往dolist集合里面添加domian 为空就返回空
                if(domain == null) {
                    return null;
                }
                doList.add(domain);
            }
        } else {
            return null;
        }
        return doList;
    }
}
